const mongoose = require('mongoose');
const glob = require('glob')
const { resolve } = require('path')
const db = 'mongodb://localhost:27017/douban-movie'
mongoose.Promise = global.Promise


//  数据库连接
exports.connect = ()=>{
    let maxConnectTimes = 0

    return new Promise((resolve,reject)=>{
        if(process.env.NODE_ENV !=='production'){
            mongoose.set('debug',true)
        }
    
        mongoose.connect(db)
    
        //  断开连接监听事件
        mongoose.connection.on('disconnected',()=>{
            maxConnectTimes++
            if(maxConnectTimes<5){
                mongoose.connect(db)
            }else{
                reject
                throw new Error('数据库挂掉了!')
            }
            
        })
    
        //  连接失败监听事件
        mongoose.connection.on('error',(err)=>{
            maxConnectTimes++
            if(maxConnectTimes<5){
                mongoose.connect(db)
            }else{
                reject
                throw new Error('数据库挂掉了!')
            }
        })
    
        //  连接打开监听事件
        mongoose.connection.on('open',()=>{
            resolve()
            console.log('MongoDB连接成功')

           /*  const Person = mongoose.model('Person',{name:String});
            const xht = new Person({name:'谢海涛'})
            xht.save().then(()=>{
                console.log('name 保存成功')
            }) */
        })
    })

}